package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @version 1.0
 * @Author 马冰
 * @Date 2024/12/11 10:54
 * @注释
 */
public class JDBCUtils {
    static DataSource dataSource;
    static{
        //Properties 用于加载配置文件
        Properties properties = new Properties();
        //通过运行时类对象获取类的加载器  通过加载器将文件转为流
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        //将流中数据加载到Properties内
        try {
            properties.load(is);

            //todo 通过Properties读取到的配置信息构建连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取连接池对象
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 通过连接池对象获取连接
     * @return
     */
    public static Connection getConnection() {

        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
